from fastapi import APIRouter, Request, HTTPException
from typing import Dict, Any, List
import logging
import uuid
from datetime import datetime
from app.models.translate_request import TranslateRequest
from app.utils.error_handling import (
    BadRequestError,
    NotFoundError,
    InternalServerError,
    ErrorHandler
)

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("translate_route_simple")

# 创建路由器
router = APIRouter(prefix="/api/v1", tags=["翻译(简化版)"])

# 模拟翻译函数
class SimpleTranslationService:
    def __init__(self):
        logger.info("初始化简化版翻译服务")
    
    def perform_translation(self, shop_domain: str, source_text: str, target_language: str, 
                          source_language: str, metadata_modle: dict = None) -> Dict[str, Any]:
        """简化版翻译功能"""
        try:
            logger.info(f"执行简化版翻译 - 店铺: {shop_domain}, 目标语言: {target_language}")
            
            # 非常简单的模拟翻译
            translated_text = f"[模拟翻译到{target_language}] {source_text}"
            
            # 特殊情况处理
            if target_language == "zh" and source_language == "en":
                if "Hello" in source_text:
                    translated_text = source_text.replace("Hello", "你好")
                elif "Thank you" in source_text:
                    translated_text = source_text.replace("Thank you", "谢谢")
            
            # 模拟积分计算
            points_needed = len(source_text) // 10
            if points_needed < 1:
                points_needed = 1
            
            return {
                "is_success": 1,
                "message": "Translation completed successfully",
                "shopify_domain": shop_domain,
                "data": {
                    "translated_text": translated_text,
                    "source_text": source_text,
                    "source_language": source_language,
                    "target_language": target_language,
                    "log_id": str(uuid.uuid4()),  # 生成模拟日志ID
                    "points_consumed": points_needed
                }
            }
        except Exception as e:
            logger.error(f"翻译过程中发生错误: {str(e)}")
            error = InternalServerError(f"Translation failed: {str(e)}")
            return ErrorHandler.handle_api_error(error, shop_domain, metadata_modle)
    
    def get_translation_history(self, shop_domain: str, limit: int, offset: int) -> List[Dict[str, Any]]:
        """获取模拟翻译历史"""
        logger.info(f"获取模拟翻译历史 - 店铺: {shop_domain}")
        # 返回模拟数据
        return [
            {
                "log_id": str(uuid.uuid4()),
                "timestamp": datetime.now().isoformat(),
                "source_text": "Hello world",
                "translated_text": "你好世界",
                "source_language": "en",
                "target_language": "zh",
                "points_consumed": 1
            }
        ]
    
    def get_translation_log(self, log_id: str) -> Dict[str, Any]:
        """获取模拟翻译日志"""
        logger.info(f"获取模拟翻译日志 - ID: {log_id}")
        # 返回模拟数据
        return {
            "log_id": log_id,
            "shop_domain": "example.myshopify.com",
            "timestamp": datetime.now().isoformat(),
            "source_text": "Hello world",
            "translated_text": "你好世界",
            "source_language": "en",
            "target_language": "zh",
            "points_consumed": 1,
            "status": "SUCCESS"
        }

# 创建服务实例
translation_service = SimpleTranslationService()

@router.post("/translate")
async def translate(request: Request, req_data: TranslateRequest) -> Dict[str, Any]:
    """
    翻译接口
    提供文本翻译服务，支持多语言互译
    """
    try:
        client_ip = request.client.host
        logger.info(f"请求来自 {client_ip}, 店铺: {req_data.shopify_domain}, 目标语言: {req_data.target_language}")
        
        # 调用简化版翻译服务
        result = translation_service.perform_translation(
            shop_domain=req_data.shopify_domain,
            source_text=req_data.text,
            target_language=req_data.target_language,
            source_language=req_data.source_language,
            metadata_modle=req_data.metadata_modle
        )
        
        return result
        
    except ValueError as e:
        logger.error(f"请求参数验证失败: {str(e)}")
        error = BadRequestError(f"Parameter validation failed: {str(e)}")
        return ErrorHandler.handle_api_error(
            error,
            shopify_domain=req_data.shopify_domain or "",
            metadata_modle=req_data.metadata_modle or ""
        )
    except Exception as e:
        logger.error(f"处理请求出错: {e}")
        return ErrorHandler.handle_generic_exception(
            e,
            shopify_domain=req_data.shopify_domain or "",
            metadata_modle=req_data.metadata_modle or ""
        )

@router.get("/translate/history/{shopify_domain}")
async def get_translation_history(shopify_domain: str, limit: int = 50, offset: int = 0) -> Dict[str, Any]:
    """
    获取翻译历史记录
    """
    # 参数验证
    if not shopify_domain or len(shopify_domain) < 3:
        error = BadRequestError("Invalid shop domain")
        return ErrorHandler.handle_api_error(error, shopify_domain)
    
    try:
        # 调用服务层获取模拟历史记录
        history = translation_service.get_translation_history(shopify_domain, limit, offset)
        
        return {
            "is_success": 1,
            "message": "Translation history retrieved successfully",
            "shopify_domain": shopify_domain,
            "data": {
                "history": history,
                "limit": limit,
                "offset": offset
            }
        }
    except Exception as e:
        logger.error(f"获取翻译历史失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, shopify_domain)

@router.get("/translate/points/history/{shopify_domain}")
async def get_translation_points_history(shopify_domain: str, limit: int = 50, offset: int = 0) -> Dict[str, Any]:
    """
    获取翻译积分交易历史
    """
    try:
        # 参数验证
        if not shopify_domain or len(shopify_domain) < 3:
            error = BadRequestError("Invalid shop domain")
            return ErrorHandler.handle_api_error(error, shopify_domain)
        
        # 返回模拟数据
        history = [
            {
                "transaction_id": str(uuid.uuid4()),
                "timestamp": datetime.now().isoformat(),
                "points_consumed": 1,
                "source_language": "en",
                "target_language": "zh",
                "text_length": 11
            }
        ]
        
        return {
            "is_success": 1,
            "message": "Translation points history retrieved successfully",
            "shopify_domain": shopify_domain,
            "data": {
                "history": history,
                "limit": limit,
                "offset": offset
            }
        }
    except Exception as e:
        logger.error(f"获取翻译积分交易历史失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, shopify_domain)

@router.get("/translate/log/{log_id}")
async def get_translation_log(log_id: str) -> Dict[str, Any]:
    """
    获取翻译日志详情
    """
    try:
        # 参数验证
        if not log_id or len(log_id) != 36:
            error = BadRequestError("Invalid log ID")
            return ErrorHandler.handle_api_error(error, "")
        
        # 调用服务层获取模拟日志详情
        log_detail = translation_service.get_translation_log(log_id)
        
        if not log_detail:
            error = NotFoundError("Translation log not found")
            return ErrorHandler.handle_api_error(error, "")
        
        return {
            "is_success": 1,
            "message": "Translation log retrieved successfully",
            "shopify_domain": log_detail.get("shop_domain", ""),
            "data": log_detail
        }
        
    except Exception as e:
        logger.error(f"获取翻译日志详情失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, "")